package com.app.twth.base;

import android.Manifest;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.FileProvider;
import androidx.databinding.ViewDataBinding;

import com.app.twth.R;
import com.app.twth.app.Constant;
import com.app.twth.app.MyApplication;
import com.app.twth.databinding.DialogCameraPhotoBinding;
import com.app.twth.databinding.DialogShowPhotoBinding;
import com.app.twth.utils.FileUtils;
import com.app.twth.utils.Loading;
import com.app.twth.utils.MyDialogUtil;
import com.app.twth.utils.PermissionChecker;
import com.app.twth.utils.PhotoBitmapUtils;
import com.app.twth.utils.Utils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;

import java.io.File;

/**
 * Created by admin on 2024/5/9.
 * Description:
 * Encoding: utf-8
 */
public abstract class BaseCameraPhotoActivity<VB extends ViewDataBinding, VM extends BaseAndroidViewModel> extends BaseActivity<VB, VM> {
    private String TAG = getClass().getSimpleName();
    public String pathName;
    public String temp_path;
    private AlertDialog dialogPhoto;
    private AlertDialog dialogCameraPhoto;
    public static final int TAKE_PICTURE = 3, IMAGE_OPEN = 1;//打开图片标记


    public void requestCamera(String name) {
        if (PermissionChecker.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            // 验证相机权限
            if (PermissionChecker.checkSelfPermission(this, Manifest.permission.CAMERA)) {
                showCameraPhotoDialog(name);
            } else {
                PermissionChecker.requestPermissions(this,
                        new String[]{Manifest.permission.CAMERA}, Constant.APPLY_CAMERA_PERMISSIONS_CODE);
            }
        } else {
            PermissionChecker.requestPermissions(this, new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE}, Constant.APPLY_STORAGE_PERMISSIONS_CODE);
        }
    }

    public void requestCameraOnly(String name) {
        if (PermissionChecker.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            // 验证相机权限
            if (PermissionChecker.checkSelfPermission(this, Manifest.permission.CAMERA)) {
                pathName = name;
                try {
                    //上传图片存放路径
                    File file = new File(MyApplication.PATH_IMG);
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
//            temp_path = MyApplication.PATH_AD + File.separator + pathName + DateUtil.getYMDHMS2() + ".jpg";
                File file = FileUtils.getCreatFilePath(pathName);
                temp_path = file.getAbsolutePath();
                Log.e(TAG, "temp_path:" + temp_path);
//            File file = new File(temp_path);
                Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                Uri imageUri;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // 7.0使用FileProvider
                    imageUri = FileProvider.getUriForFile(mContext, "com.app.twth.fileprovider", file);
                    openCameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                } else {
                    imageUri = Uri.fromFile(file);
                }
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                startActivityForResult(openCameraIntent, TAKE_PICTURE);
            } else {
                PermissionChecker.requestPermissions(this,
                        new String[]{Manifest.permission.CAMERA}, Constant.APPLY_CAMERA_PERMISSIONS_CODE);
            }
        } else {
            PermissionChecker.requestPermissions(this, new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE}, Constant.APPLY_STORAGE_PERMISSIONS_CODE);
        }
    }

    private void showCameraPhotoDialog(String name) {
        dialogCameraPhoto = MyDialogUtil.getDialog(mContext, initCameraPhotoDialogView(name), Gravity.BOTTOM);
        dialogCameraPhoto.setCanceledOnTouchOutside(true);
        dialogCameraPhoto.show();
    }

    private View initCameraPhotoDialogView(String name) {
        pathName = name;
        DialogCameraPhotoBinding dialogBinding = DialogCameraPhotoBinding.inflate(getLayoutInflater());
        dialogBinding.tvCamera.setOnClickListener(v -> {
            if (dialogCameraPhoto != null) {
                dialogCameraPhoto.dismiss();
            }
            try {
                //上传图片存放路径
                File file = new File(MyApplication.PATH_IMG);
                if (!file.exists()) {
                    file.mkdirs();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
//            temp_path = MyApplication.PATH_AD + File.separator + pathName + DateUtil.getYMDHMS2() + ".jpg";
            File file = FileUtils.getCreatFilePath(pathName);
            temp_path = file.getAbsolutePath();
            Log.e(TAG, "temp_path:" + temp_path);
//            File file = new File(temp_path);
            Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            Uri imageUri;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // 7.0使用FileProvider
                imageUri = FileProvider.getUriForFile(mContext, "com.app.twth.fileprovider", file);
                openCameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                imageUri = Uri.fromFile(file);
            }
            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(openCameraIntent, TAKE_PICTURE);


        });
        dialogBinding.tvPhoto.setOnClickListener(v -> {
            if (dialogCameraPhoto != null) {
                dialogCameraPhoto.dismiss();
            }
            try {
                //选择图片
//                Intent intent = new Intent(Intent.ACTION_PICK,
//                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//                List<ResolveInfo> resolveInfos = getPackageManager().queryIntentActivities(intent
//                        , PackageManager.MATCH_DEFAULT_ONLY);
                Intent intent = new Intent(Intent.ACTION_PICK);
//                intent.setDataAndType(
//                        MediaStore.Images.Media.INTERNAL_CONTENT_URI,
//                        "image/*");
                intent.setType(MediaStore.Images.Media.CONTENT_TYPE);
                startActivityForResult(intent, IMAGE_OPEN);

//                Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
//                getIntent.setType("image/*");
//                Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//                pickIntent.setType("image/*");
//                Intent chooserIntent = Intent.createChooser(getIntent, "Select Image");
//                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent});
//                startActivityForResult(chooserIntent, IMAGE_OPEN);
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
        dialogBinding.tvCancel.setOnClickListener(v -> {
            if (dialogCameraPhoto != null) {
                dialogCameraPhoto.dismiss();
            }
        });
        return dialogBinding.getRoot();
    }

    public void showPhotoDialog(String path) {
        Log.e(TAG, "path:" + path);
        dialogPhoto = MyDialogUtil.getDialog(mContext, initPhotoDialogView(path), Gravity.CENTER);
        dialogPhoto.setCanceledOnTouchOutside(true);
        dialogPhoto.show();
    }

    private View initPhotoDialogView(String path) {
        DialogShowPhotoBinding dialogBinding = DialogShowPhotoBinding.inflate(getLayoutInflater());
        dialogBinding.ivImg.setOnViewTapListener((v, x, y) -> {
            if (dialogPhoto != null) {
                dialogPhoto.dismiss();
            }
        });
        RequestOptions options = new RequestOptions()
                .placeholder(R.mipmap.picture_icon_editor)//图片加载出来前，显示的图片
                .fallback(R.mipmap.picture_icon_editor) //url为空的时候,显示的图片
                .error(R.mipmap.picture_icon_warning);//图片加载失败后，显示的图片
        Glide.with(mContext).load(path).apply(options).into(dialogBinding.ivImg);
        return dialogBinding.getRoot();
    }

    public void setShow(String pathImage, ImageView iv_show, ImageView iv_delete) {
        RequestOptions options = new RequestOptions()
//                .override(300)
                .placeholder(R.mipmap.picture_icon_editor)//图片加载出来前，显示的图片
                .fallback(R.mipmap.picture_icon_editor) //url为空的时候,显示的图片
                .error(R.mipmap.picture_icon_warning);//图片加载失败后，显示的图片
        Log.e(TAG, "setShow:" + pathImage);
        Glide.with(mContext)
                .load(pathImage)
                .apply(options)
                .into(iv_show);
        iv_delete.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PICTURE:
                if (resultCode == -1) {
                    try {
                        try {
                            loading = Loading.newLoading(mContext, "photo compression");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        new MyAsyncTask(temp_path, pathName).execute();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case IMAGE_OPEN:
                try {
                    if (data == null) {
                        return;
                    }
                    Uri uri = data.getData();
                    if (!TextUtils.isEmpty(uri.getAuthority())) {
                        //查询选择图片
                        Cursor cursor = getContentResolver().query(
                                uri,
                                new String[]{MediaStore.Images.Media.DATA},
                                null,
                                null,
                                null);
                        //返回  没找到选择图片
                        if (null == cursor) {
                            return;
                        }
                        //光标移动至开头  获取图片路径
                        cursor.moveToFirst();
                        temp_path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                        Log.e(TAG, "temp_path:" + temp_path);
                        try {
                            loading = Loading.newLoading(mContext, "photo compression");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        new MyAsyncTask(temp_path, pathName).execute();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    Loading loading;

    class MyAsyncTask extends AsyncTask<String, String, String> {
        String path;
        String name;

        public MyAsyncTask(String path, String name) {
            this.path = path;
            this.name = name;
        }

        @Override
        protected String doInBackground(String... strings) {
            // 得到修复后的照片路径
            String s = null;
            try {
                s = PhotoBitmapUtils.amendRotatePhoto(path, name);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return s;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            try {
                if (loading != null) {
                    loading.dismiss();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            Log.e(TAG, "onPostExecute:" + s);
            if (Utils.isEmpty(s)) {
                return;
            }
            getImgPath(s);

            try {
                if (Utils.isEmpty(temp_path)) {
                    return;
                }
                File file = new File(temp_path);
                if (file == null) {
                    return;
                }
                FileUtils.updateGallery(mContext, file);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    protected abstract void getImgPath(String path);

    public void deleteImg(ImageView iv, ImageView iv_delete) {
//        iv.setImageResource(R.drawable.ic_add_image);
        iv.post(new Runnable() {
            @Override
            public void run() {
                iv.setImageResource(R.drawable.ic_add_image);
            }
        });
        iv_delete.setVisibility(View.GONE);
    }
}
